<script setup lang="ts">
import getServiceManageInstance from '@/assets/localdatas/configurationManage/extendConfiguration/get_service_manage_instance.json'
import { useCommonStore } from '@/store/main'
import { INJECT_THEME_COLOR } from '@/common/provideType'

const $store = useCommonStore()
const THEME_COLOR = inject(INJECT_THEME_COLOR)
const formRef = ref()
const form = reactive({})
const mainParams = reactive({
	dialogVisible: false,
	dialogConfig: {
		title: '',
		width: 600,
		content: {}
	},
	instanceIdList: []
})

const openDialogFn = dialogConfig => {
    mainParams.dialogVisible = true
	mainParams.dialogConfig = dialogConfig

	form.instance_id = mainParams.dialogConfig?.content?.instance_id,
	form.key = mainParams.dialogConfig?.content?.key,
	form.value = mainParams.dialogConfig?.content?.value

	// 灰度版本，查询实例id列表
	mainParams.dialogConfig?.isGray && queryServiceManageInstanceFn()
}

// 文本域tab缩进
const textareaTabKeydown = e => e.preventDefault()
const textareaTabKeyup = () => {
	const elInput = document.querySelector('.textareaCom textarea')
	const startPos = elInput.selectionStart
	const endPos = elInput.selectionEnd
	if (startPos === undefined || endPos === undefined) return
	const insertTxt = '\t'
	const txt = elInput.value
	const result = txt.substring(0, startPos) + insertTxt + txt.substring(endPos)
	elInput.value = result
	elInput.focus()
	elInput.selectionStart = startPos + insertTxt.length
	elInput.selectionEnd = startPos + insertTxt.length
	form.value = result
}
const textareaKeyupEnter = () => {
	const elInput = document.querySelector('.textareaCom textarea')
	const startPos = elInput.selectionStart
	const endPos = elInput.selectionEnd
	if (startPos === undefined || endPos === undefined) return
	const txt = elInput.value
	const str = txt.substring(0, startPos - 1)
	const lastPos = str.lastIndexOf('\n')
	const reg = /^(\t+)/
	const regRes = reg.exec(str.substring(lastPos + 1))
	if(!regRes) return
	const len = [0].length
	let insertTxt = ''
	for(let i = 0; i < len; i++) {
		insertTxt += '\t'
	}
	const result = txt.substring(0, startPos) + insertTxt + txt.substring(endPos)
	elInput.value = result
	elInput.focus()
	elInput.selectionStart = startPos + insertTxt.length
	elInput.selectionEnd = startPos + insertTxt.length
	form.value = result
}

// 表单校验
const validateId = (rule, value, callback) => {
	if(!value) return callback(new Error('实例ID不能为空'))
	callback();
}
const validateKey = (rule, value, callback) => {
	if(!value) return callback(new Error('key不能为空'))
	const reg = /^[_0-9A-Za-z]+$/;
	if(!reg.test(value)) return callback(new Error('key只能由字母数字或下划线组成。'));
	callback();
}
const validateValue = (rule, value, callback) => {
	if(!value) return callback(new Error('value不能为空'))
	const reg = /(\n|\t)/g
	const dataValue = form['value'].replace(reg, '')
	try {
		JSON.parse(dataValue)
	} catch (e) {
		return callback(new Error('value不是一个合法的JSON'))
	}
	callback()
}
const rules = reactive({
	instance_id: [
		{required: true, validator: validateId, trigger: 'blur'}
	],
	key: [
		{required: true, validator: validateKey, trigger: 'blur'}
	],
	value: [
		{required: true, validator: validateValue, trigger: 'blur'}
	]
})

// 请求灰度版本服务实例Id(增加灰度实例时的下拉列表)
const queryServiceManageInstanceFn = async serviceName => {
	let res = await getServiceManageInstance
	if(res?.code === 0) {
		mainParams.instanceIdList = res.data
	} 
}

// 关闭弹窗
const handlerCloseFn = () => mainParams.dialogVisible = false

const confirmDialogFn = async formEl => {
	if(!formEl) return;
	await formEl.validate(valid => {
		// if(!valid) return;// 校验不通过，允许继续提交
		if(!valid) {
			if(mainParams.dialogConfig?.isGray && !form.instance_id) return
			if(form.key === '') return
			if(form.value === '') return

			ElMessageBox.confirm(
				'"Value"的值不是一个合法"Json"，是否确定要继续提交。',
				'温馨提示',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			).then(() => {
				fn(true)
			}).catch(() => {
				ElMessage({
					type: 'info',
					message: '提交操作已取消',
				})
			})
		} else {
			fn()
		}
		function fn(flag = false) {
			const reg = /(\n|\t)/g	
			const dataValue = flag ? form['value'] : form['value'].replace(reg, '')
			let content = {
				key: form['key'],
				value: dataValue
			}

			if(mainParams.dialogConfig?.isGray) {
				content['instance_id'] = form['instance_id']
			}

			const listName = mainParams.dialogConfig?.isGray 
				? 'grayData' 
				: 'mainData'


			mainParams.dialogConfig?.isAdd
				? $store.setLocalJson({
					eventType: 'add',
					listName,
					content
				})
				: $store.setLocalJson({
					eventType: 'edit',
					listName,
					content
				})

			handlerCloseFn()
		}
	})
}

defineExpose({
    openDialogFn
})
</script>

<template>
	<el-dialog
		v-if="mainParams.dialogVisible"
		v-model="mainParams.dialogVisible"
		:title="mainParams?.dialogConfig?.title"
		:width="mainParams?.dialogConfig?.width"
		:before-close="handlerCloseFn"
		:close-on-click-modal="false"
		draggable
	>
		<div>
			<el-form 
				:model="form"
				:rules="rules"
				ref="formRef"
				label-width="80px"
				@submit.native.prevent
			>
				<el-form-item v-if="mainParams.dialogConfig?.isGray" label="实例ID:" prop="instance_id" class="mb-20">
					<el-select v-if="mainParams.dialogConfig?.isAdd" v-model="form.instance_id" placeholder="请选择">
						<el-option
							v-for="item in mainParams.instanceIdList"
							:key="item"
							:label="item"
							:value="item" 
						/>
					</el-select>
					<span v-else>
						{{ form.instance_id }}
					</span>
				</el-form-item>

				<el-form-item label="Key:" prop="key" class="mb-20">
					<el-input
						v-if="mainParams.dialogConfig?.isAdd"
						v-model="form.key"
					/>
					<span v-else>
						{{ form.key }}
					</span>
				</el-form-item>

				<el-form-item label="Value:" prop="value" class="mb-20">
					<el-input
						v-model="form.value"
						class="textareaCom"
						type="textarea"
						@keydown.tab="textareaTabKeydown($event)"
						@keyup.tab="textareaTabKeyup"
						@keyup.enter="textareaKeyupEnter"
					/>
				</el-form-item>
			</el-form>
		</div>
		
		<template #footer>
			<span class="dialog-footer">
				<el-button class="btn btn-lg" @click="handlerCloseFn">
					取 消
				</el-button>
				<el-button type="primary" :class="[`btn btn-lg btn-${THEME_COLOR}`]" @click="confirmDialogFn(formRef)">
					确 定
				</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<style lang="scss" scoped>
.btn {
	width: auto;
}
:deep(.el-form) {
	label.el-form-item__label {
		display: inline-block;
		text-indent: 0;
		text-align: right;
	}
	textarea {
		height: 1.4rem;
	}
	.el-form-item.json-tips {
		margin-bottom: 0;
		.el-form-item__content {
			line-height: .2rem;
			font-size: .12rem;
		}
	}
}
</style>